package com.xiaoq;




import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xinpeng created on 16/7/9-上午9:22.
 */

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class JedisClusterConfig {

    private static Logger logger = LoggerFactory.getLogger(JedisClusterConfig.class);

    @Resource
    private RedisProperties redisProperties;

    /**
     * 注意：
     * 这里返回的JedisCluster是单例的，并且可以直接注入到其他类中去使用
     * @return jedisCluster
     */
    @Bean
    public JedisCluster getJedisCluster() {
        Set<HostAndPort> nodes = new HashSet<>();
        for(String node : redisProperties.getNodes()){

            logger.info("listing the redis cluster nodes: "+node);
            try{
                String[] parts = StringUtils.split(node, ":");
                Assert.state(parts.length==2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'");
                nodes.add(new HostAndPort(parts[0], Integer.parseInt(parts[1])));
            }catch(RuntimeException e){
                throw new IllegalStateException("Invalid redis cluster nodes property '" + node + "'", e);
            }
        }
        if(nodes.isEmpty()){
            return null;
        }
        logger.info(" maxTotal = "+redisProperties.getMaxTotal());

        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(redisProperties.getMaxTotal());
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMinIdle(redisProperties.getMinIdle());


        return new JedisCluster(nodes, redisProperties.getConnectionTimeout(), redisProperties.getSoTimeout(), redisProperties.getMaxRedirections(), config);
    }


}
